package com.abe.libphoto;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.IntDef;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.widget.Toast;

import java.io.File;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class AbeMultiMedia {

    public interface OnAbeMultiMediaCallBack {
        void onPhoto(int type, String imagePath, Bitmap bitmap);
    }

    public interface OnAbeMultiMediaListener {
        void onPhotoPath(int type, String path);
    }

    private static OnAbeMultiMediaCallBack callBack;
    private static OnAbeMultiMediaListener listener;
    private static Reference<AbeMultiMedia> multiMedia;
    private static Reference<Activity> activityReference;
    private int currentType;

    private static final String SD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
    private static final String FILE_ROOT_PATH = SD_PATH + File.separator + "photoFrame";
    private static final String VIDEO_PATH = FILE_ROOT_PATH + File.separator + "video";
    private static final String IMAGE_PATH = FILE_ROOT_PATH + File.separator + "image";
    private static String filename = "";

    public final static int TYPE_TAKE_PHOTO = 0x001;
    public final static int TYPE_ALBUM_SELECT = 0x002;

    @IntDef({TYPE_ALBUM_SELECT, TYPE_TAKE_PHOTO})
    @Retention(RetentionPolicy.SOURCE)
    public @interface MediaType {

    }

    public static AbeMultiMedia with(Activity activity) {
        if (multiMedia == null || multiMedia.get() == null) {
            multiMedia = new WeakReference<>(new AbeMultiMedia());
        }
        if (activityReference == null) {
            activityReference = new WeakReference<>(activity);
        }
        return multiMedia.get();
    }

    public AbeMultiMedia setType(@MediaType int type) {
        currentType = type;
        return multiMedia.get();
    }

    public AbeMultiMedia setListener(OnAbeMultiMediaListener tempListener) {
        listener = tempListener;
        return multiMedia.get();
    }

    public AbeMultiMedia setCallBack(OnAbeMultiMediaCallBack tempCallBack) {
        callBack = tempCallBack;
        return multiMedia.get();
    }

    public void start() {
        switch (currentType) {
            case TYPE_ALBUM_SELECT: {
                albumSelect();
            }
            break;
            case TYPE_TAKE_PHOTO: {
                takePhoto();
            }
            break;
        }
    }

    public void destroy() {
        if (callBack != null) {
            callBack = null;
        }
        if (listener != null) {
            listener = null;
        }
        if (activityReference != null) {
            activityReference.clear();
            activityReference = null;
        }
        if (multiMedia != null) {
            multiMedia.clear();
            multiMedia = null;
        }
    }

    private void albumSelect() {
        Intent picture = new Intent(
                Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        activityReference.get().startActivityForResult(picture, TYPE_ALBUM_SELECT);
    }

    private void takePhoto() {
        String authority = getAuthor(activityReference.get());
        w("authority:" + authority);
        File dir = new File(IMAGE_PATH);
        if (InspectionSDcard.checkSdcard(dir)) {
            Intent intent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
            filename = format.format(new Date()) + ".jpg";
            File f = new File(dir, filename);
            Uri u;
            //适配android7.0 手机拍照取uri的处理
            if (Build.VERSION.SDK_INT < 24) {
                u = Uri.fromFile(f);//7.0这里会闪退，imgfile是图片文件路径
                intent.putExtra(MediaStore.Images.ImageColumns.ORIENTATION, 0);
            } else {
                u = FileProvider.getUriForFile(activityReference.get(), authority, f);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
            activityReference.get().startActivityForResult(intent, TYPE_TAKE_PHOTO);
        } else {
            Toast.makeText(activityReference.get(), "没有储存卡或没有找到储存目录",
                    Toast.LENGTH_LONG).show();
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK && multiMedia != null && activityReference != null) {
            switch (requestCode) {
                case TYPE_TAKE_PHOTO: {
                    File file = new File(IMAGE_PATH);
                    String[] JPGFile = file.list();
                    String picturePath = "";
                    for (String name : JPGFile) {
                        if (filename.equals(name)) {
                            File f = new File(IMAGE_PATH + File.separator + filename);
                            picturePath = f.getAbsolutePath();
                            break;
                        }
                    }
                    if (!TextUtils.isEmpty(picturePath)) {
                        if (callBack != null) {
                            callBack.onPhoto(requestCode, picturePath, BitmapUtil.readLocalBitmap(picturePath));
                        }
                        if (listener != null) {
                            listener.onPhotoPath(requestCode, picturePath);
                        }
                    }
                }
                break;
                case TYPE_ALBUM_SELECT: {
                    if (data != null) {
                        Uri selectedImage = data.getData();
                        String[] filePathColumns = {MediaStore.MediaColumns.DATA};
                        if (selectedImage != null) {
                            Cursor c = activityReference.get().getContentResolver().query(selectedImage,
                                    filePathColumns, null, null, null);
                            if (c != null) {
                                c.moveToFirst();
                                int columnIndex = c.getColumnIndex(filePathColumns[0]);
                                String picturePath = c.getString(columnIndex);
                                c.close();
                                if (!TextUtils.isEmpty(picturePath)) {
                                    if (callBack != null) {
                                        callBack.onPhoto(requestCode, picturePath, BitmapUtil.readLocalBitmap(picturePath));
                                    }
                                    if (listener != null) {
                                        listener.onPhotoPath(requestCode, picturePath);
                                    }
                                }
                            }
                        }
                    }
                }
                break;
            }
        }
    }

    private static void w(String msg) {
        System.out.println("AbeMultiMedia:" + msg);
    }

    private static String getAuthor(Context context) {
        String author = "";
        try {
            ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            Bundle bundle = ai.metaData;
            author = bundle.getString("photo_author");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return author;
    }
}
